const Monitor = require('../../utils/monitor.js').Monitor
const util = require('../../utils/util.js')
Page(Monitor.hookApp({
  data: {
    imgUrl: getApp().globalData.imgUrl,
    imgUrls: getApp().globalData.imgUrls,
    clock: `${getApp().globalData.imgUrl}jsy-newshop时间.svg`,
    kefu: `${getApp().globalData.imgUrl}jsy-newshop客服 (2).svg`,
    qingdan: `${getApp().globalData.imgUrl}jsy-newshop清单.svg`,
    lock: true
  },
  submit() { // 提交订单
    if (this.data.lock) {
      this.setData({
        lock: false
      })
      this.pay(this.data.order_id)
    } else {
      setTimeout(() => {
        this.setData({
          lock: true
        })
      }, 2000)
    }

  },
  cancel() { // 取消
    let that = this
    wx.showModal({
      title: '提示',
      content: '确认取消订单？',
      cancelText: '否',
      confirmText: '是',
      success(res) {
        if (res.confirm) {
          util.API('pyapi/Cancellation_order', {
            order_id: that.data.order_id
          }, 'application/x-www-form-urlencoded').then(res => {
            let {
              code,
              msg
            } = res
            if (code == 200) {
              setTimeout(() => {
                wx.reLaunch({
                  url: `../dingDanList/dingDanList?status=99`,
                })
              }, 200)
            } else {
              wx.showToast({
                title: msg,
                icon: 'none'
              })
            }
          })
        }
      }
    })

  },

  pay(order_id) { // 支付
    util.API('pyapi/create_order', {
      parent_id: this.data.parent_id,
      market_type_id: this.data.market_type_id || 0,
      activity_id: this.data.activity_id || 0,
      market_type: this.data.market_type || 0,
      order_id: order_id,
      operation: "pay"
    }, 'application/x-www-form-urlencoded').then(res => {
      let {
        code,
        data,
        pay,
        msg
      } = res
      let that = this
      if (code == 200) {
        wx.requestPayment({ //吊起微信支付
          timeStamp: pay.data.timeStamp,
          nonceStr: pay.data.nonceStr,
          package: pay.data.package,
          signType: pay.data.signType,
          paySign: pay.data.paySign,
          success: function(res) {
            setTimeout(() => {
              if (parseInt(that.data.market_type) == 0) {
                wx.navigateTo({
                  url: `../DingDanXiangTiJiao/DingDanXiangTiJiao?order_id=${pay.c_order_id}&distribution=${that.data.distribution}&from=faile`,
                })
              } else if (parseInt(that.data.market_type) == 1) {
                wx.navigateTo({
                  url: `/elsePage/pages/pinTuanXianQing/pinTuanXianQing?order_id=${pay.c_order_id}&market_type=${that.data.market_type}`,
                })
              }
            }, 200)
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    })
  },
  onUnload() {
    clearInterval(this.data.interval);
  },
  getOrderInfo(order_id) {
    util.API('pyapi/create_order', {
      order_id: order_id
    }, 'application/x-www-form-urlencoded').then(({
      code,
      msg,
      totalFee,
      data
    }) => {
      if (code == 200) {
        data.orders_goods_list = this.specifications(data.orders_goods_list) // 转换商品格式
        let cTime = this.setTimeStamp(data.ctime)
        util.intervalTime(data.ctime + 86400, this, 1000)
        let {
          orders_goods_list,
          all,
          pay_order,
          distribution,
          amount_discount
        } = data
        this.setData({
          orders_goods_list,
          all,
          totalFee: totalFee.totalFee,
          tootlePrise: data.sum2 + data.sum1,
          Address: totalFee.Address,
          pay_order,
          distribution,
          amount_discount,
          cTime
        })
      }
    })
  },
  onLoad(o) {
    // 获取订单详情
    this.setData({
      parent_id: o.parent_id || 0,
      market_type_id: o.market_type_id || 0,
      activity_id: o.activity_id || 0,
      market_type: o.market_type || 0,
      order_id: o.order_id
    })
  },
  onShow() {
    this.getOrderInfo(this.data.order_id)
  },


  specifications(trg) { //商品规格转换
    let len = trg.length
    for (let i = 0; i < len; i++) {
      let size = ''
      let str = `${trg[i].sku_type}`
      trg[i].sku_type = JSON.parse(str)
      for (let j = 0; j < trg[i].sku_type.length; j++) {
        for (let prop in trg[i].sku_type[j]) {
          size += trg[i].sku_type[j][prop] + " / "
        }
      }
      trg[i].size = size
      trg[i].size = trg[i].size.substring(0, trg[i].size.length - 3)
    }
    return trg
  },
  contact(e) { // 联系客服
    var that = this
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      wx.showToast({
        title: '未授权',
        icon: 'none'
      })
    } else {
      var that = this
      wx.request({
        url: getApps.URL + 'wxcheck/wxcheck/decryptData',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          appid: getApps.wx_appid,
          sessionKey: getApps.loginData.session_key
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        }, // 设置请求的 header
        success: function(res) {
          res.data = JSON.stringify(res.data)
          util.API('wxcheck/wxcheck/savephone', {
            openid: getApps.loginData.openid,
            phone: res.data.phoneNumber
          }).then(res => {
            if (res.code == 200) {
              wx.showToast({
                title: '绑定成功',
              })
            }
          })
        }
      })

    }
  },
  setTimeStamp(inputTime) { //转换时间戳
    let time = util.getTimeDian(inputTime)
    return `${time.y}-${time.m}-${time.d} ${time.h}:${time.i}:${time.s}`
  }
}))